package net.wanho.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.validation.Payload;
import java.util.Calendar;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-07-27 13:47
 * Description：JWT工具类
 */
public class JwtUtils {

    private static final int MINUTE=30;
    private static final String SECRET = "wanho";

    /**
     * 生成令牌
     * @param payload
     * @return
     */
    public static String generate(Map<String,Object> payload){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE,MINUTE);

        String token = JWT.create()
                .withPayload(payload)
                .withExpiresAt(c.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 生成令牌
     * @param payload
     * @param expire 过期时间，单位分钟
     * @return
     */
    public static String generate(Map<String,Object> payload, int expire){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE,expire);

        String token = JWT.create()
                .withPayload(payload)
                .withExpiresAt(c.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证令牌
     * @param token 令牌串
     * @return 校验成功返回true，失败抛出异常
     */
    public static boolean valid(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取令牌中的载荷
     * @param token
     * @return
     */
    public static Integer parseInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long parseLong(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String parseString(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }

    /**
     * 反码令牌
     * @param token
     * @return
     */
    public static Integer decodeInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long decodeLong(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String decodeString(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asString();
    }

}
